package DataFile;

import java.nio.ByteBuffer;
import java.util.Formatter;
import java.util.LinkedList;

/**
 * Table for Exception Handlers.
 * @author Roman Richter, Dominik Ollesz
 * @date 05.05.2011
 */
public class Structure_ExceptionsTable extends Structure_Template {

	LinkedList<short[]> exceptionsTable = 
		new LinkedList<short[]>();
	
	int exceptions_count = 0;
	
	public Structure_ExceptionsTable() {
		// do nothing
	}
	
	/**
	 * @return Elements inside ExceptionsTable.
	 */
	public int size() {
		return exceptions_count;	
	}

	/**
	 * Set a new base address (4 Bit aligned).
	 */
	protected int setBaseAddress(int newBaseAdress) {
		while ((newBaseAdress%4)!=0) {
			newBaseAdress++;
		}
		baseAdress=newBaseAdress;
		return(baseAdress+getMemorySize());
	}
	
	protected int getMemorySize() {
		int mySize = (exceptions_count > 0) ? SHORT_WIDTH*2 : 0;
			mySize += exceptions_count * SHORT_WIDTH; // content
		return(mySize);
	}
	
//	protected int getTableDataMemorySize() {
//		int mySize=0;
//		if (exceptionsTable != null) {
//			mySize += exceptionsTable.size()*SHORT_WIDTH;
//		}
//		return(mySize);
//	}
	
	protected String getMemoryMapAsString() {
		String returnString = "\nExceptions Table : Base Address - ";

		returnString+=getAdressAsHexString(baseAdress);
		returnString+=" : size - "+getMemorySize();
		returnString+="\n";
	
		int count=0;
		for (short[] i : exceptionsTable) {
			for (short element : i) {
				returnString+="" + new Formatter().format("%03d",count++) + " index #" + element +"\n"; 
			}
		}
		
		return(returnString);
	}

	protected String getMemoryMapAsString(Structure_CP_Table cpTable) {
		String returnString = "\nExceptions Table : Base Address - ";

		returnString+=getAdressAsHexString(baseAdress);
		returnString+=" : size - "+getMemorySize();
		returnString+="\n";
	
		int count=0;
		for (short[] i : exceptionsTable) {
			for (short element : i) {
				returnString+="" + new Formatter().format("%03d",count++) + " index #" + element +
				" -> " + cpTable.getClassName(element) + "\n"; 
			}
		}
		
		return(returnString);
	}
	
	@Override
	public void writeData(ByteBuffer fileData) {
		fileData.position(baseAdress-DataFileCreator.BASE_MEMORY_ADRESS);

		// write content of exceptions table
		if ((exceptionsTable != null) && (exceptions_count > 0)){
			
			fileData.putShort((short)exceptions_count);    // 2 Bytes: length
			fileData.putShort((short)0);                   // 2 Bytes: dummy
			
			for (short[] i : exceptionsTable) {
				for (short element : i) {
					fileData.putShort((short)element);		//  2 Bytes
				}
			}
		} 
	}
	
	/**
	 * 
	 */
	public void addExceptions(short[] exceptions) {
		if (exceptions != null) {
			exceptionsTable.add(exceptions);
			exceptions_count += exceptions.length;
		}
	}
	
}
